/*
 * Copyright 2009 Max Kugland
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.splink.deepsplink.navigation {
	import org.splink.library.tree.INode;
	import org.splink.library.tree.Tree;

	/**
	 * The <code>IPageNavigationModel</code> default implementation. 
	 * 
	 * @see org.splink.deepsplink.navigation.IPageNavigationModel
	 * 
	 * @author Max Kugland
	 */
	final internal class PageNavigationModel implements IPageNavigationModel {
		private var _rootNode : INode;
		private var _subPageIds : Array;
		private var _pageId : String;

		public function PageNavigationModel(pageId : String, tree : Tree) {
			_pageId = pageId;
			_rootNode = tree.root;
			_subPageIds = computeSubPageIds(pageId);
		}

		private function computeSubPageIds(pageId : String) : Array {
			var node : INode = Tree.getNodeById(pageId, _rootNode);
			var ar : Array = new Array();
			for each (var n : INode in node.children) {
				ar.push(n.id);
			}
			return ar;
		}

		private function getParentChainIds(id : String) : Array {
			var node : INode = Tree.getNodeById(id, _rootNode);
			var parentChainIds : Array = new Array();
			if(node == null) return parentChainIds;
			var ar : Array = Tree.getParentNodeChain(node);
			for each (var n : INode in ar) {
				parentChainIds.push(n.id);
			}
			parentChainIds.push(id);
			return parentChainIds;
		}

		/**
		 * @inheritDoc
		 */
		public function getSubPageIds() : Array {
			return _subPageIds;
		}

		/**
		 * @inheritDoc
		 */
		public function getSelectedPageId(selectedPageId : String) : String {
			var selectedParentChainIds : Array = getParentChainIds(selectedPageId);
			for each (var selectedParentPageId : String in selectedParentChainIds) {
				for each (var subPageId : String in _subPageIds) {
					if(subPageId == selectedParentPageId) {
						return subPageId;
					}
				}
			}

			var pageParentChainIds : Array = getParentChainIds(_pageId);
			for each (var parentPageId : String in pageParentChainIds) {
				if(parentPageId == selectedPageId) {
					return parentPageId;
				}
			}
			
			return null;
		}

		/**
		 * @inheritDoc
		 */
		public function finalize() : void {
			_rootNode = null;
			_subPageIds = null;
		}
	}
}
